﻿using System;
using System.Configuration;
using System.Net.Configuration;
using System.Web;
using System.Web.Configuration;
using System.Web.Mail;
using Newtonsoft.Json.Converters;

namespace eCommerce.core.Helpers
{
    public class Utils
    {

        #region Cache String
        public static string GET_PROPERTY_LISTBY_PARENTID(int parentId)
        {
            return "GET_PROPERTY_LISTBY_PARENTID_" + parentId;
        }
        public static string GET_PRODUCT_GETLISTFILTER(string lstCategory, string lstPropertyValue, string orderBy, int pageIndex, int pageSize)
        {
            return "GET_PRODUCT_GetListFilter_" + lstCategory + "_" + lstPropertyValue + "_" + orderBy + "_" + pageIndex + "_" + pageSize;
        }

        public static string GET_PRODUCT_GETLISTLATEST(int count, int status)
        {
            return "GET_PRODUCT_GETLISTLATEST_" + count + "_" + status;
        }

        public static string GET_PRODUCT_GETLISTLATEST_PAGING( int status, int pageIndex, int pageSize)
        {
            return "GET_PRODUCT_GETLISTLATEST_PAGING_" + status + "_" + pageIndex + "_" + pageSize;
        }

        public static string GET_PRODUCT_GETLISTDISCOUNT(int count)
        {
            return "GET_GETLISTDISCOUNT_" + count;
        }

        public static string GET_PRODUCT_GETLISTDISCOUNT_PAGING( int pageIndex, int pageSize)
        {
            return "GET_PRODUCT_GETLISTLATEST_PAGING_" + pageIndex + "_" + pageSize;
        }

        public static string GET_ARTICLE_LISTPAGINATION(int categoryId, int pageIndex, int pageSize)
        {
            return "GET_ARTICLE_LISTPAGINATION_" + categoryId + "_" + pageIndex + "_" + pageSize;
        }

        public static string GET_ARTICLE_GETBYCATID(int categoryId)
        {
            return "GET_ARTICLE_GETBYCATID_" + categoryId;
        }

        public static string GET_CATEGORY_GETLISTBYPARENTID(int typeId, int parentId, int isActive)
        {
            return "GET_CATEGORY_GETLISTBYPARENTID_" + typeId + "_" + parentId + "_" + isActive;
        }

        public static string GET_CATEGORY_GETBYID(int id)
        {
            return "GET_CATEGORY_GETBYID_" + id;
        }

        public static string GET_PRODUCT_GETLISTPROPERTY(int productId)
        {
            return "GET_Product_GetListProperty_" + productId;
        }
        
        #endregion

        /***************************************
        = Query String Name
        -------------------------------------- */
        // system
        public static string ControlId      = "cId";
        public static string UserControlId  = "ucId";
        public static string GroupId        = "gId";
        public static string MenuId         = "mId";
        public static string UserId         = "uId";
        public static string AdminUserId    = "adminUserId";
        public static string UserName       = "username";
       
        public static string Active       = "active";
        public static string Action       = "action";
        public static string Priority     = "priority";
        public static string Status       = "status";
        public static string Parent_Name  = "parent_name";
        public static string ParentName   = "parentName"; 
        public static string Name         = "name";
        public static string PageType     = "pagetype";
        public static string Cat_url      = "cat_url";    
        public static string Title        = "title";
        public static string Sapo         = "sapo";
        public static string Content      = "content";
        public static string Source       = "source";
        public static string ImagePath    = "imgPath";
        public static string PublishOn    = "publishOn";
        public static string CustomerId   = "customerId";
        public static string StoreId      = "storeId";
        public static string OrderBy      = "orderBy";
        public static string OrderId      = "oId";
        public static string Mobile       = "mobile";
        public static string Email        = "email";
        public static string Address      = "address";
        public static string Description  = "desc";
        public static string UnitPrice    = "uPrice";
        public static string SpecialPrice = "sPrice";
        public static string FilePath     = "filePath";

        public static string Id         = "id";        
        public static string TypeId     = "tId";
        public static string SizeType   = "sTypeId";
        public static string TypeName   = "typeName";
        public static string ParentId   = "pId";
        public static string ArticleId  = "aId";
        public static string DiscountId = "dId";
        public static string ExpensId   = "eId";
        public static string CategoryId = "cId";
        public static string ProductId  = "pId";        
        public static string SizeId     = "sId";
        public static string NoteId     = "nId";
        public static string IeId       = "ieId";
        public static string IeDetailId = "iedId";
                
        public static string LstCategory        = "lstCategory";
        public static string LstProduct         = "lstProduct";
        public static string LstPropertyValue   = "lstPropertyValue";

        public static string isExactly       = "isExactly";
        public static string IsAdministrator = "isAdministrator";

        public static string TotalValue = "totalValue";
        public static string Percent = "percent";

        // common
        public static string ThumbnailSize = "size";
        public static string Keyword       = "keyword";
        public static string PageIndex     = "pi";
        public static string PageSize      = "ps";
        public static string StartDate     = "sd";
        public static string EndDate       = "ed";

        public static void ClearAllCache()
        {
            var enumerator = HttpContext.Current.Cache.GetEnumerator();
            while (enumerator.MoveNext())
                HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
        }

        public static IsoDateTimeConverter SerializeFormat(string format)
        {
            var converter2 = new IsoDateTimeConverter {DateTimeFormat = format};
            return converter2;
        }

        public static int CalcItemIndex(int dataItemIndex, int pageIndex, int pageSize)
        {
            return (pageSize * (pageIndex - 1) + dataItemIndex + 1);
        }

        /***************************************
        = Sample Message
        -------------------------------------- */
        public static string NoData
        {
            get { return ShowMessage(string.Empty, "Không có dữ liệu", MessageType.Information); }
        }

        public static string ShowMessage(string message, MessageType messageType)
        {
            return ShowMessage(string.Empty, message, messageType);
        }

        public static string ShowMessage(string title, string message, MessageType messageType)
        {
            var msg = !string.IsNullOrEmpty(title)
                      ? "<div class=\"nNote {0} hideit\"><p><strong>" + title + "</strong>{1}</p></div>"
                      : "<div class=\"nNote {0} hideit\"><p>{1}</p></div>";

            switch (messageType)
            {
                case MessageType.Failure:
                    return string.Format(msg, "nFailure", message);
                case MessageType.Information:
                    return string.Format(msg, "nInformation", message);
                case MessageType.Success:
                    return string.Format(msg, "nSuccess", message);
                case MessageType.Warning:
                    return string.Format(msg, "nWarning", message);
            }
            return "";
        }

        /***************************************
        = Get Setting From Webconfig
        -------------------------------------- */
        public static string GetMainConnectionString()
        {
            return GetConnectionString("MainConnectionString");
        }

        public static string GetConnectionString(string key)
        {
            return !string.IsNullOrEmpty(WebConfigurationManager.ConnectionStrings[key].ConnectionString) ? WebConfigurationManager.ConnectionStrings[key].ConnectionString : "";    
        }

        public static object GetSetting(string key, SettingType settingType)
        {
            switch (settingType)
            {
                    case SettingType.Int32:
                        return !string.IsNullOrEmpty(WebConfigurationManager.AppSettings[key]) ? int.Parse(WebConfigurationManager.AppSettings[key]) : 0;
                    case SettingType.Int64:
                        return !string.IsNullOrEmpty(WebConfigurationManager.AppSettings[key]) ? long.Parse(WebConfigurationManager.AppSettings[key]) : 0;
                    case SettingType.String:
                        return !string.IsNullOrEmpty(WebConfigurationManager.AppSettings[key]) ? WebConfigurationManager.AppSettings[key] : string.Empty;
                    case SettingType.Bool:
                        return !string.IsNullOrEmpty(WebConfigurationManager.AppSettings[key]) && bool.Parse(WebConfigurationManager.AppSettings[key]);
                    case SettingType.ConnectionString:
                        return WebConfigurationManager.ConnectionStrings[key].ConnectionString;
            }
            return string.Empty;
        }

        /***************************************
        = Get Value From Query String
        -------------------------------------- */
        public static long GetIdFromRequestString(string requestString, long defaultId)
        {
            requestString = HttpContext.Current.Request.QueryString[requestString];
            return requestString != null ? int.Parse(requestString) : defaultId;
        }

        public static int GetIdFromRequestString(string requestString, int defaultId)
        {
            requestString = HttpContext.Current.Request.QueryString[requestString];
            return requestString != null ? int.Parse(requestString) : defaultId;
        }

        public static bool GetIdFromRequestString(string requestString, bool defaultId)
        {
            requestString = HttpContext.Current.Request.QueryString[requestString];
            return requestString == "false" ? bool.Parse(requestString) : defaultId;
        }

        public static string GetIdFromRequestString(string requestString, string defaultId)
        {
            requestString = HttpContext.Current.Request.QueryString[requestString];
            return requestString ?? defaultId;
        }

        /***************************************
        = Format Price
        -------------------------------------- */
        public static string FormatPrice(decimal number)
        {
            string format;

            if (number == 0)
                format = "";
            else
                if (number >= 1000 || number <= -1000)
                    format = String.Format("{0:0,0}", number);
                else
                    format = String.Format("{0:0}", number);

            try { format = format.Replace(",", "."); }
            catch { }

            return format;
        }

        /***************************************
        = Convert
        -------------------------------------- */
        public static long ToLong(object obj)
        {
            long retVal;

            try
            {
                retVal = Convert.ToInt64(obj);
            }
            catch
            {
                retVal = 0;
            }

            return retVal;
        }

        public static int ToInt32(object obj)
        {
            int retVal;

            try
            {
                retVal = Convert.ToInt32(obj);
            }
            catch
            {
                retVal = 0;
            }

            return retVal;
        }

        public static int ToInt32(object obj, int defaultValue)
        {
            int retVal;

            try
            {
                retVal = Convert.ToInt32(obj);
            }
            catch
            {
                retVal = defaultValue;
            }
            return retVal;
        }

        public static string ToString(object obj)
        {
            string retVal;

            try
            {
                retVal = Convert.ToString(obj);
            }
            catch
            {
                retVal = String.Empty;
            }

            return retVal;
        }

        public static DateTime ToDateTime(object obj)
        {
            DateTime retVal;
            try
            {
                retVal = Convert.ToDateTime(obj);
            }
            catch
            {
                retVal = DateTime.Now;
            }
            if (retVal == new DateTime(1, 1, 1)) return DateTime.Now;

            return retVal;
        }

        public static DateTime ToDateTime(object obj, DateTime defaultValue)
        {
            DateTime retVal;
            try
            {
                retVal = Convert.ToDateTime(obj);
            }
            catch
            {
                retVal = DateTime.Now;
            }
            if (retVal == new DateTime(1, 1, 1)) return defaultValue;

            return retVal;
        }

        public static bool ToBoolean(object obj)
        {
            bool retVal;

            try
            {
                retVal = Convert.ToBoolean(obj);
            }
            catch
            {
                retVal = false;
            }

            return retVal;
        }

        public static double ToDouble(object obj)
        {
            double retVal;

            try
            {
                retVal = Convert.ToDouble(obj);
            }
            catch
            {
                retVal = 0;
            }

            return retVal;
        }

        public static double ToDouble(object obj, double defaultValue)
        {
            double retVal;

            try
            {
                retVal = Convert.ToDouble(obj);
            }
            catch
            {
                retVal = defaultValue;
            }

            return retVal;
        }

        public static decimal ToDecimal(object obj)
        {
            decimal retVal;

            try
            {
                retVal = Convert.ToDecimal(obj);
            }
            catch
            {
                retVal = 0;
            }

            return retVal;
        }

        public static decimal ToDecimal(object obj, decimal defaultValue)
        {
            decimal retVal;

            try
            {
                retVal = Convert.ToDecimal(obj);
            }
            catch
            {
                retVal = defaultValue;
            }

            return retVal;
        }

        /***************************************
        = Unicode
        -------------------------------------- */
        public const string UniChars =
            "àáảãạâầấẩẫậăằắẳẵặèéẻẽẹêềếểễệđìíỉĩịòóỏõọôồốổỗộơờớởỡợùúủũụưừứửữựỳýỷỹỵÀÁẢÃẠÂẦẤẨẪẬĂẰẮẲẴẶÈÉẺẼẸÊỀẾỂỄỆĐÌÍỈĨỊÒÓỎÕỌÔỒỐỔỖỘƠỜỚỞỠỢÙÚỦŨỤƯỪỨỬỮỰỲÝỶỸỴÂĂĐÔƠƯ";

        public const string KoDauChars =
            "aaaaaaaaaaaaaaaaaeeeeeeeeeeediiiiiooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAAEEEEEEEEEEEDIIIOOOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYYAADOOU";

        public static string Unsign(string s)
        {
            var retVal = String.Empty;
            for (var i = 0; i < s.Length; i++)
            {
                var pos = UniChars.IndexOf(s[i].ToString());
                if (pos >= 0)
                    retVal += KoDauChars[pos];
                else
                    retVal += s[i];
            }
            return retVal;
        }

        public static string UnsignAndDash(string s)
        {
            if (!string.IsNullOrEmpty(s))
            {
                var retVal = String.Empty;
                for (int i = 0; i < s.Length; i++)
                {
                    var pos = UniChars.IndexOf(s[i].ToString());
                    if (pos >= 0)
                        retVal += KoDauChars[pos];
                    else
                        retVal += s[i];
                }
                retVal = retVal.Replace("-", "");
                retVal = retVal.Replace("  ", "");
                retVal = retVal.Replace(" ", "-");
                retVal = retVal.Replace("--", "-");
                retVal = retVal.Replace(":", "");
                retVal = retVal.Replace(";", "");
                retVal = retVal.Replace("+", "");
                retVal = retVal.Replace("@", "");
                retVal = retVal.Replace(">", "");
                retVal = retVal.Replace("<", "");
                retVal = retVal.Replace("*", "");
                retVal = retVal.Replace("{", "");
                retVal = retVal.Replace("}", "");
                retVal = retVal.Replace("|", "");
                retVal = retVal.Replace("^", "");
                retVal = retVal.Replace("~", "");
                retVal = retVal.Replace("]", "");
                retVal = retVal.Replace("[", "");
                retVal = retVal.Replace("`", "");
                retVal = retVal.Replace(".", "");
                retVal = retVal.Replace("'", "");
                retVal = retVal.Replace("(", "");
                retVal = retVal.Replace(")", "");
                retVal = retVal.Replace(",", "");
                retVal = retVal.Replace("”", "");
                retVal = retVal.Replace("“", "");
                retVal = retVal.Replace("?", "");
                retVal = retVal.Replace("\"", "");
                retVal = retVal.Replace("&", "");
                retVal = retVal.Replace("$", "");
                retVal = retVal.Replace("#", "");
                retVal = retVal.Replace("_", "");
                retVal = retVal.Replace("=", "");
                retVal = retVal.Replace("%", "");
                retVal = retVal.Replace("…", "");
                retVal = retVal.Replace("/", "");
                retVal = retVal.Replace("\\", "");
                return retVal.ToLower();
            }
            return string.Empty;
        }

        /***************************************
        = DateTime
        -------------------------------------- */
        public static string FormatDateVietNam(DateTime dt)
        {
            return string.Format("{0}-{1}-{2}", dt.Day, dt.Month, dt.Year);
        }

        public static string FormatTimeVietNam(DateTime dt)
        {
            return string.Format("{0}:{1}:{2}", dt.Hour, dt.Minute, dt.Second);
        }

        public static string ValidStrDateTime(string dt)
        {
            try
            {
                var isCheck = dt.Contains("/");
                var splitDateTime = dt.Split(isCheck ? '/' : '-');

                var validDateTime = string.Format("{0}/{1}/{2}", splitDateTime[2], splitDateTime[1], splitDateTime[0]);
                return validDateTime;
            }
            catch
            {
                return "";
            }
        }

        public static DateTime ValidDateTime(string dt)
        {
            var isCheck = dt.Contains("/");
            var splitDateTime = dt.Split(isCheck ? '/' : '-');

            var validDateTime = string.Format("{0}/{1}/{2}", splitDateTime[2], splitDateTime[1], splitDateTime[0]);
            return ToDateTime(validDateTime);
        }

        public static DateTime ValidDateTime(string date, string hhmmsss)
        {
            var isCheck = date.Contains("/");
            var splitDateTime = date.Split(isCheck ? '/' : '-');

            var validDateTime = string.Format("{0}/{1}/{2} {3}", splitDateTime[2], splitDateTime[1], splitDateTime[0], hhmmsss);
            return ToDateTime(validDateTime);
        }

        public static string FormatIn_HHMM_DDMMYYYY(DateTime dt)
        {
            string sDay;
            string sMonth;
            string sHour;
            string sMin;

            if (dt.Hour < 10)
            {
                sHour = "0" + dt.Hour;
            }
            else
                sHour = dt.Hour.ToString();
            if (dt.Minute < 10)
            {
                sMin = "0" + dt.Minute;
            }
            else
                sMin = dt.Minute.ToString();
            if (dt.Month < 10)
            {
                sMonth = "0" + dt.Month;
            }
            else
                sMonth = dt.Month + "";
            if (dt.Day < 10)
            {
                sDay = "0" + dt.Day;
            }
            else
                sDay = dt.Day + "";

            return sHour + ":" + sMin + " - " + sDay + "/" + sMonth + "/" + dt.Year;
        }

        public static string FormatIn_DDMMYYYY(DateTime dt)
        {
            string sDay;
            string sMonth;
            string sHour;
            string sMin;

            if (dt.Hour < 10)
            {
                sHour = "0" + dt.Hour;
            }
            else
                sHour = dt.Hour.ToString();
            if (dt.Minute < 10)
            {
                sMin = "0" + dt.Minute;
            }
            else
                sMin = dt.Minute.ToString();
            if (dt.Month < 10)
            {
                sMonth = "0" + dt.Month;
            }
            else
                sMonth = dt.Month + "";
            if (dt.Day < 10)
            {
                sDay = "0" + dt.Day;
            }
            else
                sDay = dt.Day + "";

            return sDay + "/" + sMonth + "/" + dt.Year;
        }

        /***************************************
        = Send Mail
        -------------------------------------- */
        public static bool SendMail(string to, string subject, string body)
        {
            try
            {
                var smtpSec = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

                // Initialize the mailmessage class
                var mailMsg = new MailMessage
                {
                    From = smtpSec.Network.UserName,
                    To = to,
                    Subject = subject,
                    BodyFormat = MailFormat.Html,
                    Body = body,
                    Priority = MailPriority.High,
                    BodyEncoding = System.Text.Encoding.UTF8
                };

                // Smtp configuration
                SmtpMail.SmtpServer = smtpSec.Network.Host;
                mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", smtpSec.Network.DefaultCredentials);
                mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", smtpSec.Network.UserName);
                mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", smtpSec.Network.Password);
                mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", smtpSec.Network.Port.ToString());
                mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");

                SmtpMail.Send(mailMsg);
                return true;
            }
            catch { return false; }
        }

        public static string GetOrderStatus(int status)
        {
            switch (status)
            {
                case 1:
                    return "Đặt hàng";
                case 2:
                    return "Đã thanh toán";
                case 4:
                    return "Đã xóa";
                case 8:
                    return "Khách lẻ";
                default:
                    return "Không biết :(";
            }
        }

        public static string GetPathImg()
        {
            string path = string.Empty;
            if (ConfigurationManager.AppSettings["CssFile"].ToString().IndexOf("blue") != -1)
            {
                path = "/blue";
            }
            else if (ConfigurationManager.AppSettings["CssFile"].ToString().IndexOf("orange") != -1)
            {
                path = "/orange";
            }
            else if (ConfigurationManager.AppSettings["CssFile"].ToString().IndexOf("yellow") != -1)
            {
                path = "/yellow";
            }
            else if (ConfigurationManager.AppSettings["CssFile"].ToString().IndexOf("red") != -1)
            {
                path = "/red";
            }
            else if (ConfigurationManager.AppSettings["CssFile"].ToString().IndexOf("green") != -1)
            {
                path = "/green";
            }
            else if (ConfigurationManager.AppSettings["CssFile"].ToString().IndexOf("pink") != -1)
            {
                path = "/pink";
            }

            return path;
        }

        public static bool IsAllowDistributedCached
        {
            get
            {
                return (ConfigurationManager.AppSettings["AllowDistCache"] == "1");
            }
        }

        public static T GetFromCacheIIS<T>(string cacheName)
        {
            if (IsAllowDistributedCached)
            {
                object data = HttpContext.Current.Cache[cacheName];
                if (null != data)
                {
                    try
                    {
                        return (T)data;
                    }
                    catch
                    {
                        return default(T);
                    }
                }
                else
                {
                    return default(T);
                }
            }
            else
                return default(T);
        }


    }
}
